﻿using iTool.Common.Result;
using iTool.PluginCore.Server;
using Microsoft.Extensions.Configuration;
using System;

namespace iToolPlugin.SMSProvider
{
    public class QCloudSMSProvider : ILServerPlugin
    {
        public string Name { get; }

        private readonly IConfiguration configuration;
        public QCloudSMSProvider(IConfiguration configuration)
        {
            this.Name = "QCloudSMSProvider";
            this.configuration = configuration;
        }

        [ExportMethod("Send")]
        public MethodResult<string> Send(string toPhone, int enums)
        {
            try
            {
                int smscode = new Random().Next(100000, 999999);

                SMSService sms = new SMSService(new SMSService.SMSParameter
                {
                    toPhone = toPhone,
                    context = smscode.ToString(),
                    sign = this.configuration.GetSection("QCloud")?.GetSection("SMSSign")?.Value ?? String.Empty,
                    templateId = enums,
                    appid = int.Parse(this.configuration.GetSection("QCloud")?.GetSection("appid")?.Value ?? "0"),
                    appkey = this.configuration.GetSection("QCloud")?.GetSection("appkey")?.Value ?? String.Empty,
                });

                var result = sms.Send();

                if (result.result == 0)
                {
                    return new MethodResult<string> { IsFinished = true, Data = smscode.ToString() };
                }
                else
                {
                    return new MethodResult<string> { IsFinished = false, Discription = result.errMsg };
                }
            }
            catch (Exception e)
            {

                return new MethodResult<string> { IsFinished = false, Discription = e.Message };
            }
        }
    }
}
